"use strict";

var app = angular.module('userBoardApp', ['angularFileUpload']).
  directive('showErrors', crabii.validation_directive);

app.controller('userBoardController', function($scope, $http, FileUploader) {
  var $ = jQuery;
  var settings = Drupal.settings;
  $scope.boards = [];

  // reset board
  $scope.reset = function() {
    $scope.$broadcast('crabii-show-errors-reset');
    $scope.board = $.extend(true, {}, settings.user_board.board); // clone the object

    $('.user-board-errors').empty();
  }

  // calling reset first to initiate the form
  $scope.reset();

  var get_url = '/board/' + settings.user_board.uid + '/get';
  var post_url = '/board/' + settings.user_board.uid  + '/post';

  // uploader object
  var uploader = $scope.uploader = new FileUploader({
    url: post_url,
    queueLimit: 1,
    removeAfterUpload: true,
    alias: 'files[file]'
  });

  /**
   * get boards from remote url
   */
  function getBoards() {
    $http.get(get_url).success(function (data) {
      $scope.boards = data;
    });
  }

  /**
   *  helper function for collecting form data
   */
  function getFormData() {
    return {
      tid: $scope.board.tid,
      name: $scope.board.name,
      category: $scope.board.field_category.und[0].value,
      privacy: $scope.board.field_privacy.und[0].value,
      user_board_token: settings.user_board.user_board_token
    }
  }

  /**
   * fire after successfully submit the form
   */
  function afterBoardCreation(data) {
    $('#user-board-form button').prop('disabled', false);
    var errors = data.errors || [];
    if(errors.length > 0) {
      var errors = '<ul class="list-unstyled">';
      angular.forEach(data.errors, function(value, key) {
        errors += '<li>' + value + '</li>';
      });
      errors += '</ul>';
      $('.user-board-errors').append(errors);
    } else {
      getBoards();
      setTimeout(function() {$('#user-board-form').modal('hide');}, 500); //need to settimeout to prevent error:inprog
    }
  }

  // calling get boards
  getBoards();

  /**
   * creating boards handler
   */
  $scope.createBoard = function () {
    $scope.$broadcast('crabii-show-errors-check-validity');

    $scope.showErrorsCheckValidity = true;

    if (!$scope.userBoardForm.$valid) {
      return;
    }

    $('#user-board-form button').prop('disabled', true);
    if(uploader.queue.length > 0) {
      uploader.uploadAll();
    } else {
      $http({
        method: 'POST',
        url: post_url,
        data: jQuery.param(getFormData()),
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
      }).success(function (data) {
        afterBoardCreation(data);
      });
    }
  }

  // CALLBACKS
  uploader.onBeforeUploadItem = function(item) {
    var formData = [getFormData()];
    Array.prototype.push.apply(item.formData, formData);
  };
  uploader.onCompleteItem = function(item, response, status, headers) {
    afterBoardCreation(response);
  }
});

jQuery(document).ready(function($) {
  var $scope = angular.element('.grid-boards-wrapper').scope(); // get $scope

  $('#user-board-form').on('hidden.bs.modal', function(){
    $scope.$apply(function() {
      $scope.reset();
    });
  });
});
